import { reactive, ref, Ref, nextTick, readonly } from 'vue';
import _ from 'lodash';
import { Message } from '@arco-design/web-vue';

import { useFilmReadRight, useFilmReadHeader, useFilmReadLeft } from '@/store';
import usePageRight from "../../../../pageRight/hooks/usePageRight";
import { saveYaYData, submitDataOver } from '@/api/readPathology/readPathology';
import type { CommonListItem } from '@/api/common/common.d';
import type { CallBackData } from '@/components/dialog/type.d';

interface CallBack {
  flag: boolean;
  status: string;
}

export default function useToolBarRight(provideState: { getToolBarItem: Function }) {
  const FilmReadRight = useFilmReadRight();
  const FilmReadLeft = useFilmReadLeft();
  const FilmReadHeader = useFilmReadHeader();
  const PageRight = usePageRight();
  // 阴阳性是否展示
  const radioVisible = ref<boolean>(false);
  // 阴阳性选择值
  const radioChecked = ref<boolean | undefined>(undefined);
  // 阴阳性点击
  const handleRadioClick = async (type: number) => {
    if (FilmReadHeader.seriesList?.length !== 0) {
      radioChecked.value = type === 1;
      const params = {
        arId: FilmReadHeader.seriesList! && FilmReadHeader.seriesList[0].id,
        yay: type,
      };
      const res = await saveYaYData(params);
    }
  };
  // 标记废片显示值
  const markScrapVisible = ref<boolean>(false);

  // 标记废片选项集合
  const scrapList = ref<CommonListItem[]>([]);

  // 标记废片选项值
  const scrapValue = ref<string>('');
  // 标记废片备注值
  const discardRemark = ref<string>('');

  // 提交显示值
  const submitVisible = ref(false);

  // 提交
  const handleSubmit = () => {
    submitVisible.value = true;
  };
  let tempType = '';
  // 提交弹窗事件
  const handleSubmitVisible = (data: CallBack) => {
    tempType = data.status;
    if (data.status === 'save') {
      // 单序列提交
      validateForm(data.flag);
    } else {
      // 多序列提交
      validateForm(data.flag);
    }
  };
  let currentIndex = 0;
  let seriesFormStatus = false;
  let mjorSignsFormStatus = false;
  // 校验表单
  const validateForm = async (flag: boolean) => {
    // 判定阴阳性是否选择
    if (radioVisible.value && radioChecked.value === undefined) {
      Message.error({
        content: '请选择阴阳性，再提交病理切片！',
        closable: true,
        duration: 10000,
      });
    } else {
      if (FilmReadRight.seriesSettings) {
        // 处理大征象
        const seriesValidateRes = await PageRight.seriesSetFormRef.value?.validate();
        if (seriesValidateRes === undefined) {
          seriesFormStatus = true;
          // 从病灶列表第一项开始依次聚焦来衔接小征象的校验
          submitVisible.value = flag;
          const showLesionListVal = FilmReadLeft.showLesionList;
          if (showLesionListVal.length) {
            const oneDisease = _.cloneDeep(
              showLesionListVal[currentIndex].disease
            );
            FilmReadRight.currentSubmenuItem = '';
            FilmReadRight.currentMiniSeriesSet.value = _.cloneDeep({
              formId: 0,
              formOptions: [],
              form: {},
            });
            FilmReadRight.currentSubmenuItem = String(oneDisease.id);
            FilmReadRight.currentMiniSeriesSet.value = _.cloneDeep(oneDisease.seriesList);
          }
          // 处理小征象
          nextTick(async () => {
            const mjorSignsRes = await PageRight.mjorSignsFormRef.value?.validate();
            if (mjorSignsRes === undefined) {
              submitVisible.value = flag;
              _validateForm(currentIndex, flag);
            } else {
              // 弹出错误信息
              Object.keys(mjorSignsRes).forEach((key) => {
                Message.error({
                  content: `标注征象-${mjorSignsRes[key].label}不可为空！`,
                  closable: true,
                  duration: 10000,
                });
              });
              submitVisible.value = flag;
            }
          });
        } else {
          // 弹出错误信息
          Object.keys(seriesValidateRes).forEach((key) => {
            Message.error({
              content: `序列征象-${seriesValidateRes[key].label}不可为空！`,
              closable: true,
              duration: 10000,
            });
          });
        }
        submitVisible.value = flag;
      }
    }
  };

  // 校验小征象辅助函数
  const _validateForm = async (index: number, flag: boolean) => {
    if (index === FilmReadLeft.showLesionList.length - 1) {
      mjorSignsFormStatus = true;
      submitVisible.value = flag;
      if (seriesFormStatus && mjorSignsFormStatus && tempType === 'save') {
        const params = {
          arIdList: FilmReadHeader.seriesList! && [FilmReadHeader.seriesList[0].id],
          status: 2,
        };
        const res = await submitDataOver(params);
        Message.success('保存成功！');
        submitVisible.value = flag;
        setTimeout(() => {
          window.opener = null;
          window.open('', '_self');
          window.close();
        }, 1000);
      } else {
        if (FilmReadHeader.seriesList?.length && FilmReadHeader.seriesList?.length <= 1) {
          sectionVisible.value = true;
        } else {
          const params = {
            arIdList: FilmReadHeader.seriesList! && [FilmReadHeader.seriesList[0].id],
            status: 2,
          };
          const res = await submitDataOver(params);
          Message.success('保存成功！');
          submitVisible.value = flag;
          FilmReadHeader.seriesList?.splice(0, 1)!;
          if (FilmReadHeader.seriesList?.length === 0) {
            sectionVisible.value = true;
          } else {
            setTimeout(() => {
              window.opener = null;
              window.open(window.location.href, '_self');
            }, 1000);
          }
        }
      }
      return;
    } else {
      index++;
    }
    const showLesionListVal = FilmReadLeft.showLesionList;
    if (showLesionListVal.length) {
      const oneDisease = _.cloneDeep(showLesionListVal[index].disease);
      FilmReadRight.currentSubmenuItem = '';
      FilmReadRight.currentMiniSeriesSet.value = _.cloneDeep({
        formId: 0,
        formOptions: [],
        form: {},
      });
      FilmReadRight.currentSubmenuItem = String(oneDisease.id);
      FilmReadRight.currentMiniSeriesSet.value = _.cloneDeep(oneDisease.seriesList);
    }
    nextTick(async () => {
      const mjorSignsRes = await PageRight.mjorSignsFormRef.value?.validate();
      if (mjorSignsRes === undefined) {
        _validateForm(index, flag);
      } else {
        // 弹出错误信息
        Object.keys(mjorSignsRes).forEach((key) => {
          Message.error({
            content: `标注征象-${mjorSignsRes[key].label}不可为空！`,
            closable: true,
            duration: 10000,
          });
        });
        submitVisible.value = flag;
      }
    });
  };

  // 已无新切片弹窗显示值
  const sectionVisible = ref(false);

  // 无新切片点击事件
  const handleSectionVisible = (data: CallBackData) => {
    if (data.status === 'save') {
      data.done(true);
      sectionVisible.value = data.flag;
      setTimeout(() => {
        window.opener = null;
        window.open('', '_self');
        window.close();
      }, 1000);
    }
  };

  // mpr的保存
  const handleMprSave = () => {
    provideState.getToolBarItem(() => {
      return {
        isSave: true
      }
    });
  }

  // 标记废片点击
  const handleMarkDesert = () => {
    // initScrapData();
    markScrapVisible.value = true;
  };

  // 标记废片弹窗事件
  const handleMarkScrapVisible = async (data: CallBackData) => {
    if (data.status === 'save') {
      data.done(true);
      // markScrapVisible.value = data.flag;
      const params = {
        arIdList: FilmReadHeader.seriesList! && [FilmReadHeader.seriesList[0].id],
        status: 3,
        discardCode: scrapValue.value,
        discardRemark: discardRemark.value,
      };
      const res = await submitDataOver(params);
      Message.success('保存成功！');
      markScrapVisible.value = data.flag;
      setTimeout(() => {
        window.opener = null;
        window.open('', '_self');
        window.close();
      }, 1000);
    } else {
      scrapValue.value = '';
      discardRemark.value = '';
      markScrapVisible.value = data.flag;
    };
  };

  // 提交弹窗右上角×关闭
  const handleCancel = () => {
    submitVisible.value = false;
  };

  // 上一个
  const handlePrevClick = () => {

  };
  // 下一个
  const handleNextClick = () => {

  };

  return {
    radioVisible,
    radioChecked,
    markScrapVisible,
    submitVisible,
    sectionVisible,
    scrapList,
    scrapValue,
    discardRemark,
    handleRadioClick,
    handleMarkDesert,
    handleSubmit,
    handleMarkScrapVisible,
    handleSubmitVisible,
    handleSectionVisible,
    handleCancel,
    handlePrevClick,
    handleNextClick,
    handleMprSave
  };
}
